<?php

namespace App\Admin\Actions\ShopOrderReturn;

use App\Library\Logic\AddressLogic;
use App\Library\Logic\OperateLogLogic;
use App\Library\Logic\ShopUserAddressLogic;
use App\Library\Service\Payment\WechatService;
use App\Models\ShopOrderReturnModel;
use Encore\Admin\Actions\Response;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;

class ShopOrderReturnPartGoodsAction extends ShopOrderReturnAuction
{
    public $name = '部分退款';//退货退款

    /**
     * handle
     * @param ShopOrderReturnModel $model
     * @param Request $request
     * @return Response
     */
    public function handle(ShopOrderReturnModel $model, Request $request): Response
    {
        if ((int)$model->or_type !== 1) return $this->response()->error('参数错误')->refresh();
        $address = [];
        if (!empty($request->addressId)) {
            $address = ShopUserAddressLogic::detail($request->addressId);
            if (is_null($address)) return $this->response()->error('地址错误')->refresh();
        }
        $this->saveModel($model, 5);
        $model->or_real_price = $request->amount;
        $model->or_note = $request->reason;
        $model->or_contacts = $address->ua_contacts ?? null;
        $model->or_contacts_mobile = $address->ua_contacts_mobile ?? null;
        $model->or_contacts_address = $address->ua_address_full ?? null;
        $model->save();
        payLog(WechatService::refund($model)->toArray());
        OperateLogLogic::add(Admin::user()->user_id, 'admin.orderReturn.partGoods');
        self::salesHandle($model, '请退货');
        return $this->response()->success('操作成功')->refresh();
    }

    /**
     * handle
     * @param ShopOrderReturnModel $model
     * @return void
     */
    public function form(ShopOrderReturnModel $model): void
    {
        $ensurePrice = $model->or_ensure_price * 1;
        $str = "用户申请金额 ￥$model->or_real_price 订单保证金：￥{$ensurePrice}（发货后保证金不退）";
        $this->text('amount', '退款金额')->attribute('maxlength', 10)->required();
        $this->text('reason', '退款原因')->attribute('maxlength', 255);
        $this->select('addressId', '选择地址')/*->required()*/ ->help($str)
            ->options(AddressLogic::getReturnAddress($model->sell_user_id));
    }
}
